var express = require("express");
var router = express.Router();
var {
    checkSession
} = require("../utils/index");
var {
    Mvs,
    Comment
} = require("../utils/model")
var moment = require("moment")

router.get("/test", (req, res) => {
    res.send("test-test-comment")
})

router.get("/index", (req, res) => {
    checkSession(req, res, () => {
        var {
            mid
        } = req.query;
        var obj = {};
        if (mid) {
            obj = {
                id: mid
            }
        }
        const findOneData = function (obj, callback) {
            Mvs.findOne(obj)
                .then(result => {
                    callback(result);
                })
        }
        findOneData(obj, (result) => {
            res.render("comment", {
                username: req.session.username,
                result
            })
        })
    })
})

//提交评论
router.post("/submit", (req, res) => {
    const query = req.query;
    const body = req.body;
    console.log(query)
    console.log(body)
    checkSession(req, res, () => {
        Mvs.findOne({
            id: query.mid,
        }).then(movie => {
            body.time = new Date();
            body.author = req.session.username;
            body.mid = query.mid;
            body.movie = movie;
            Comment.insertMany(body)
                .then(result => {
                    res.redirect("/comment/mlist")
                })
        })
    })
})

//评论列表
router.get("/mlist", (req, res) => {
    checkSession(req, res, () => {
        var{
            pageSize,
            page
        } = req.query;
        var total = 0;
        var totalPage = 0;
        pageSize = pageSize * 1 || 10;
        page = page * 1 || 1;

        Comment.find({},{})
        .then(data =>{
            total = data.length;
            totalPage = Math.ceil(total/pageSize);
            page = page < 1 ? 1 : page;
            page = page > totalPage ? totalPage : page

            Comment.find({}, {})
            .skip((page - 1) * pageSize)
            .limit(pageSize)
            .sort({_id:-1})
            .then(result => {
                res.render("mlist", {
                    username: req.session.username,
                    result,
                    total,
                    page,
                    pageSize,
                    totalPage,
                    logintime:moment(req.session.logintime).format('llll'),
                })
            })
        })

        
    })
})

//当前电影评论
router.get("/moviepin",(req,res)=>{
    checkSession(req,res,()=>{
        var {mid} = req.query;
        Comment.find({
            mid
        },{})
        .sort({_id:-1})
        .then(result=>{
            res.render("moviepin",{
                result,
                movie:result[0].movie,
                username:req.session.username,
                logintime:moment(req.session.logintime).format('llll'),
            })
        })
    })
})

//所有电影评论
router.get("/my",(req,res) => {
    checkSession(req,res,()=>{
        const {author} = req.query;
        Comment.find({
            author
        })
        .sort({_id:-1})
        .then(result=>{
            res.render("my",{
                result,
                author,
                username:req.session.username,
                logintime:moment(req.session.logintime).format('llll'),
            })
        })
    })
})

//评论详情
router.get("/detail",(req,res)=>{
    checkSession(req,res,()=>{
        const {_id} = req.query;
        Comment.findOne({
            _id
        })
        .then(result=>{
            res.render("detail",{
                result,
                username:req.session.username,
                logintime:moment(req.session.logintime).format('llll'),
            })
        })
    })
})

//回复评论
router.post("/answersubmit",(req,res)=>{
    checkSession(req,res,()=>{
        var {
            _id,
            subtitle 
        } = req.body;
        Comment.findOne({
            _id
        })
        .then(data=>{
            var answer = data.answer || [];
            console.log(answer);
            answer.push({
                subtitle,
                id:answer.length,
                author:req.session.username,
                logintime:moment(req.session.logintime).format('llll'),
            });
            Comment.updateMany({
                _id
            },{
                $set:{
                    answer
                }
            }).then(result=>{
                res.json({
                    code:200,
                    msg:"回复评论成功",
                    result,
                    type:1
                })
            })
        })
    })
})

// 删除评论 
router.post("/delsubmit",(req,res)=>{
    checkSession(req,res,()=>{
        var {_id} = req.body;
        Comment.remove({
            _id
        }).then(result=>{
            res.json({
                code:200,
                msg:"删除评论成功",
                result,
                type:1
            })
        })
    })
})

// 修改评论页面 
router.get("/update",(req,res)=>{
    checkSession(req,res,()=>{
        var {
            _id 
        } = req.query;
        Comment.findOne({
            _id
        }).then(result=>{
            result = {...result._doc,logintime:moment(req.session.logintime).format('llll'),}
            res.render("update",{
                result,
                movie:result.movie,
                username:req.session.username
            })
        })
    })
})

// 修改评论
router.post("/updatesumbit",(req,res)=>{
    checkSession(req,res,()=>{
        var body = req.body;
        body.time = new Date();
        Comment.updateMany({
            _id:req.query._id
        },{
            $set:body
        }).then(result=>{
            res.redirect("/comment/mlist")
        }).catch(err=>{

        })
    })
})

var multiparty = require("multiparty")
var fs = require("fs")
// 上传图片
router.post("/uploadImg",(req,res)=>{
    const form = new multiparty.Form();
    form.encoding = "utf-8"
    form.uploadDir = "./uploadtemp"  // 临时文件中转站
    form.maxFilesSize = 8*1024*1024;  // 2M 
    form.parse(req,function(err,fields,files){
        if(err) {
            console.log(err)
            res.send("<script>alert('图片过大,请重新上传');location.reload()'</script>")
        }
        var uploadUrl = "/images/upload/",
        file  = files['filedata'], // 图片信息
        originalFilename = file[0].originalFilename, // 文件名
        tempath = file[0].path;
        var timestamp = new Date().getTime(); // 时间戳
        uploadUrl += timestamp+originalFilename;  // 1.jpg ==> 15112341231.jpg
        var newPath = "./public"+uploadUrl;  // 最后路径 
        var fileRead = fs.createReadStream(tempath);
        var fileWrite = fs.createWriteStream(newPath);
        fileRead.pipe(fileWrite);
        fileWrite.on("close",()=>{
            fs.unlinkSync(tempath);
            res.json({
                err:"",
                msg:uploadUrl
            })
        })
    })
})

// 在线聊天 
router.get('/chat',(req,res)=>{
    checkSession(req,res,()=>{
        res.render("chat",{
            username:req.session.username
        })
    })
})

module.exports = router;